#include "../stdafx.h"
#include "Gather.h"
CGather::CGather()
{
	capability = 10;
	pData = (void * *)malloc(capability*sizeof(void *));
	for(long i = 0 ; i < capability;i++)
	{
		*(pData+i) = NULL;
	}
	length = 0;
}

CGather::~CGather()
{
	free(pData);
}

void CGather::Expand()
{
	void ** pData_temp;
	long capability_temp = 2*capability;
	long i;
	pData_temp = (void * *)malloc(capability_temp*sizeof(void *));
	for( i = 0 ; i< capability_temp ;i ++)
	{
		*(pData_temp+i) = NULL;
	}
	for(i = 0 ; i< length ;i ++)
	{
		*(pData_temp+i) = *(pData+i);
	}
	free(pData);
	pData = pData_temp;
	capability = capability_temp;
}

void CGather::AddToChain(void *Target)
{
	if(length>=capability-1)
	{
		Expand();
	}
	*(pData+length) = Target;
	length ++;
}

void * CGather::GetElement(long element_pos)
{
	if(element_pos<0 || element_pos>=length)
	{
		return NULL;
	}
	return *(pData+element_pos);
}

void CGather::DeleteElement(long element_pos)
{
	if(element_pos<0 || element_pos>=length)
	{
		return ;
	}
	for(long i = element_pos ; i < length-1 ; i ++)
	{
		*(pData+i) = *(pData+i+1);
	}
	length --;
	*(pData+length) = NULL;
	return ;
}

long CGather::GetElementNum()
{
	return length;
}

void CGather::Insert(void *Target, long pos)
{

	long i;
	if(pos == length)
	{
		this->AddToChain(Target);
		return ;
	}
	if(length<pos||pos<0)
	{
		return ;
	}
	if(length>=capability-1)
	{
		Expand();
	}
	for( i = length; i >pos ;)
	{
		*(pData+i) = *(pData+i-1);
		i --;
	}
	*(pData+pos) = Target;
	length ++;
}

void CGather::Empty()
{
	long i;
	for( i = 0 ; i < length ; i ++)
	{
		*(pData+i) = NULL;
	}
	length = 0;
}
